#include<string>
#include<vector>
#include<array>
#include<unordered_map>
#include<algorithm>
#include<limits>
#include <stack>
#include<iostream>
#include<sstream>
#include<deque>
#include<queue>
#define MOD 1000000007

class Solution
{
public:
    std::array<int, 5> move = {-1, 0, 1, 0, -1};

    int maxDistance(std::vector<std::vector<int>>& grid)
    {
        
        std::queue<std::pair<int, int>> q;
        int n = grid.size();
        int m = grid[0].size();
        std::vector<std::vector<bool>> visited(n, std::vector<bool>(m, false));
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (grid[i][j] == 1)
                {
                    q.emplace(i, j);
                    visited[i][j] = true;
                }
            }
        }
        int speed = 0;
      if (q.size() == n*n)
      {
          return -1;
      }
        std::cout << q.size();
        while (!q.empty())
        {
            int size = q.size();
            speed++;
            while (size--)
            {
                std::pair<int, int> cur = q.front();
                q.pop();
                grid[cur.first][cur.second] = speed;
                
                for (int i = 0; i < 4; i++)
                {
                    if (cur.first + move[i] < 0 || cur.second + move[i + 1] < 0 || cur.first + move[i] >= n || cur.
                        second + move[i + 1] >= m || visited[cur.first + move[i]][cur.second+move[i+1]]) continue;
                    std::pair<int, int> next = {cur.first + move[i], cur.second + move[i + 1]};
                    q.push(next);
                    visited[cur.first + move[i]][cur.second+move[i + 1]] = true;
                }
            }
            
        }
        return speed-1;
    }
};
